import http from "./http";
import { ApiResponse } from "./types/ApiResponse";
import tokenApi from "@/api/tokenApi";
import HttpCode from "@/api/httpCode";

/**
 * 查询当前用户的
 */
export const selectVerificationCode = (account: string) => {
  const reqData = {
    account: account
  };
  return http.doPost("/AuthApp/user/selectVerificationCode/account", reqData);
};
export const isRequireVerificationCode = (account: string) => {
  const reqData = {
    account: account
  };
  return http.doPost(`/AuthApp/user/isRequireVerificationCode/account`, reqData);

};

/**
 * 账号登录
 * @param data
 * @returns {Promise<AxiosResponse<T>>}
 */
export interface LoginAccountRequest {
  /**
   * 登录账号
   */
  account: string,
  /**
   * 登录密码
   */
  password: string,
  /**
   * 验证码
   */
  verificationCode?: string
}

export interface LoginAccountResponse {
  token: string,
  expiresTime: number,
  expires: number,
  extended: any
  refreshToken: any,
}

/**
 * 当前用户
 */
export interface CurrentUser {
  account: string,
  admin: boolean,
  deptCode: string,
  headImgAddress: string,
  nickName: string,
  userId: string,
  username: string,
  roleCodes: string[]
}

/**
 * 使用账号密码登录
 * @param data
 */
export const loginAccount = (data: LoginAccountRequest): Promise<ApiResponse<LoginAccountResponse>> => {
  return http.doPost("/AuthApp/user/login/account", data);
};
export const doModifyPassword = (data: any): Promise<ApiResponse<LoginAccountResponse>> => {
  return http.doPost("/AuthApp/user/modifyPassword", data);
};
/**
 *
 */
export const getCurrentUser = async (): Promise<ApiResponse<CurrentUser>> => {
  return http.doPost("/AuthApp/user/currentUserInfo");
};
export const loginRefreshToken = (data: any): Promise<ApiResponse<LoginAccountResponse>> => {
  return http.doPost("/AuthApp/user/login/refreshToken", data);
};
/**
 * 使用刷新token登录
 */
export const doRefreshTokenLogin = async (): Promise<Boolean> => {
  return new Promise((r, e) => {
    const refreshToken = tokenApi.getRefreshToken();
    if (refreshToken&&typeof refreshToken != "undefined") {
      loginRefreshToken({ account: refreshToken }).then((msg) => {
        const data = msg.data;
        if (msg.code == HttpCode.OK) {
          tokenApi.setToken(data.token, data.expires);
          r(true);
        } else {
          tokenApi.clearRefreshToken();
          e(false);
        }
      }).catch(err => {
        tokenApi.clearRefreshToken();
        e(false);
      });

    }
  });
};
export default {
  doRefreshTokenLogin,
  getCurrentUser,
  loginAccount,
  selectVerificationCode,
  doModifyPassword,
  isRequireVerificationCode
};
